package com.ym9527.controller;


import com.ym9527.controller.entity.OkAE;
import com.ym9527.entity.*;
import com.ym9527.entity.bin.ListSearchBean;
import com.ym9527.jpa.*;
import com.ym9527.utils.R;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

//这是帖子操作相关实体类
@RestController
@RequestMapping("loatandfound")
public class LostAndFoundController {

   @Resource
   LostAndFoundJpa lostAndFoundJpa;

   @Resource
   ResponseMessageJpa responseMessagejpa;

   @Resource
   ImageInfoJpa imageInfoJpa;

   @Resource
   UseJpa userJpa;

   @Resource
   LostLabelJpa lostLabelJpa;

   @Resource
   LabelJpa labelJpa;


   /**
    * 这是获取全部帖子
    * @return
    */
   @PostMapping("list")
   @Transactional()
   public R getAllList(@RequestBody ListSearchBean listSearchBean){

      List<LostAndFoundRequest> list=lostAndFoundJpa.findAll();

      Collections.reverse(list);

      list.forEach(item->{
         User user=userJpa.getById(item.getCreateUserId());
         item.setCreatUserName(user.getUserName());
      });



      List<LostAndFoundRequest> reList=new LinkedList<>();
      list.forEach(item->{

         if(item.getState().equals("未找到")){

            List<Label> labels=new LinkedList<>();
            List<LostLabel> lostLabels=lostLabelJpa.findByLostId(item.getLostId());

            lostLabels.forEach(itemz2->{
               Label label=labelJpa.findById(itemz2.getLabelId()).orElse(null);
               labels.add(label);
            });
            item.setLabels(labels);
            reList.add(item);
         }

      });

      //这里再过一遍筛选
      if(null!=listSearchBean){
         System.err.println("当前listSearchBean参数不为NUll");
         if(null!=listSearchBean.getDateS()||null!=listSearchBean.getTagS()||null!=listSearchBean.getTitle()||null!=listSearchBean.getText()
            &&!"".equals(listSearchBean.getTypeValue())
         ){
            System.err.println("当前进入筛选环节");
            List<LostAndFoundRequest> reListZ=new LinkedList<>();

            reList.forEach(item->{

               int fi=5;

               if(!"".equals(listSearchBean.getTypeValue())){

                 if(item.getLostType().equals(listSearchBean.getTypeValue())){
                    fi=fi-1;
                 }

               }else{
                  fi=fi-1;
               }


               if(null!=listSearchBean.getDateS()&&listSearchBean.getDateS().size()>=1){
                  System.err.println(item.getCreateTime());
                  System.err.println(listSearchBean.getDateS().get(0));
                  System.err.println(listSearchBean.getDateS().get(1));

                  System.err.println(item.getCreateTime().after(listSearchBean.getDateS().get(0)));
                  System.err.println(item.getCreateTime().before(listSearchBean.getDateS().get(1)));
                  if(item.getCreateTime().after(listSearchBean.getDateS().get(0))&&item.getCreateTime().before(listSearchBean.getDateS().get(1))){
                     fi=fi-1;
                  }


               }else{
                  fi=fi-1;
               }

               if(null!=listSearchBean.getTagS()&&listSearchBean.getTagS().size()>=1){

                  List<LostLabel> lableS=lostLabelJpa.findByLostId(item.getLostId());

                  AtomicReference<Boolean> sSi= new AtomicReference<>(new Boolean(false));

                  lableS.forEach(itemZ->{
                     listSearchBean.getTagS().forEach(itemTa->{
                        if(itemTa==itemZ.getLabelId()){
                          sSi.set(true);
                        }
                     });
                  });

                  if(sSi.get()==true){
                     fi=fi-1;
                  }

               }else{
                  fi=fi-1;
               }

               if(null!=listSearchBean.getTitle()&&!"".equals(listSearchBean.getTitle())){

                 if(item.getTitle().indexOf(listSearchBean.getTitle())!=-1){
                    fi=fi-1;
                 }

               }else{
                  fi=fi-1;
               }

               if(null!=listSearchBean.getText()&&!"".equals(listSearchBean.getText())){

                  if(item.getText().indexOf(listSearchBean.getText())!=-1){
                     fi=fi-1;
                  }

               }else{
                  fi=fi-1;
               }

               System.err.println(fi);
               if(fi==0){
                  reListZ.add(item);
               }

            });


            return R.ok(reListZ);
         }

      }


      return  R.ok(reList);

   }

   /**
    * 这是获取帖子的全部消息
    * @return
    */
   @GetMapping("messagelist")
   @Transactional()
   public R getMessageAllList(@RequestParam Long lostId){

      LostAndFoundRequest lostAndFoundRequest=lostAndFoundJpa.findById(lostId).orElse(null);

      /**
       * 这是获取补充的图片详情
       */
      List<ImgList> list=imageInfoJpa.findByLostId(lostId);
      List<String> StringList=new LinkedList<>();

      /**
       * 这是获取当前帖子的全部回复
       */
      List<ResponseMessage> messagesList=responseMessagejpa.findBySendLostId(lostId);

      messagesList.forEach(item->{

         String userName=userJpa.getById(item.getSendUserId()).getUserName();

         item.setSentUserName(userName);

      });



      list.forEach(item->{
         StringList.add(item.getImagePath());
      });

      lostAndFoundRequest.setImages(StringList);

      Collections.reverse(messagesList);
      lostAndFoundRequest.setMessages(messagesList);


      return R.ok(lostAndFoundRequest);
   }


   /**
    * 这是发布帖子方法
    * @return
    */
   @PostMapping("add")
   @Transactional()
   public R LostAndFoundAdd(HttpServletRequest request,@RequestBody LostAndFoundRequest lostAndFoundRequest){

      lostAndFoundRequest.setCreateTime(new Date());

      Long userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();
      lostAndFoundRequest.setCreateUserId(userId);



      LostAndFoundRequest re=lostAndFoundJpa.save(lostAndFoundRequest);

      lostAndFoundRequest.getLabels().forEach(item->{

         LostLabel label=new LostLabel();
         label.setLabelId(item.getLabelId());
         label.setLostId(re.getLostId());
         lostLabelJpa.save(label);
      });

      return  R.ok(re);
   }

   /**
    * 这是回复帖子消息方法
    * @return
    */
   @PostMapping("addmessage")
   @Transactional()
   public R LostAndFoundAddMessage(HttpServletRequest request,@RequestBody ResponseMessage responseMessage){

      Long userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();

      LostAndFoundRequest lostAndFoundRequest=lostAndFoundJpa.getById(responseMessage.getSendLostId());
      lostAndFoundRequest.setLostMessageTime(new Date());
      lostAndFoundJpa.save(lostAndFoundRequest);
      responseMessage.setSendTime(new Date());
      responseMessage.setSendUserId(userId);
      responseMessagejpa.save(responseMessage);

      return R.ok("回复成功!");

   }


   @DeleteMapping("deletemessage")
   @Transactional()
   public R DeleteMessage(HttpServletRequest request,@RequestBody ResponseMessage responseMessage){

      User user=userJpa.findByUserName(request.getHeader("user").split("-")[0]);

      if(user.getUserName().equals("admin")){

         responseMessagejpa.deleteById(responseMessage.getMessageId());

         return R.ok("");
      }else{

         return R.error("当前只有管理员可以删除评论");
      }





   }


   /**
    * 这是删除帖子方法
    * @return
    */
   @DeleteMapping("delete")
   @Transactional()
   public R LostAndFoundAddMessageDelete(HttpServletRequest request,@RequestBody LostAndFoundRequest lostId){

      LostAndFoundRequest lostAndFoundRequest=lostAndFoundJpa.findById(lostId.getLostId()).orElse(null);

      User userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]);

      if(lostAndFoundRequest.getCreateUserId()==userId.getUserId()||userId.getUserName().equals("admin")){
         lostAndFoundJpa.deleteById(lostId.getLostId());
         return R.ok("删除成功！");
      }else{
         return R.error("删除失败！");
      }



   }

   /**
    *
    * 这是获取某个用户发送的全部帖子
    * @return
    *
    */
   @GetMapping("getusersendaLl")
   @Transactional()
   public R getUserSendLost(HttpServletRequest request){

      Long userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();

      List<LostAndFoundRequest> list=lostAndFoundJpa.findByCreateUserId(userId);

      list.forEach(item->{

         List<LostLabel> lList=lostLabelJpa.findByLostId(item.getLostId());
         List<Label> lzList=new LinkedList<>();
         lList.forEach(item2->{
            Label label=labelJpa.findById(item2.getLabelId()).orElse(null);
            lzList.add(label);
         });

         item.setLabels(lzList);
      });


      Collections.reverse(list);
      return R.ok(list);
   }


   @PostMapping("lostandfoundok")
   @Transactional()
   public R lostAndFoundOk(HttpServletRequest request,@RequestBody OkAE okAE){

      Long userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();

      LostAndFoundRequest list=lostAndFoundJpa.findByCreateUserIdAndLostId(userId,okAE.getLostId());

      list.setState("已找到");

      lostAndFoundJpa.save(list);

      return R.ok(list);
   }


   /**
    * 这是管理员 删除帖子方法
    * @param request
    * @param lostId
    * @return
    */
   @DeleteMapping("admindeletelost")
   @Transactional()
   public R adminDelete(HttpServletRequest request,@RequestParam("lostId") Long lostId){

      Long userId=userJpa.findByUserName(request.getHeader("user").split("-")[0]).getUserId();

      LostAndFoundRequest list=lostAndFoundJpa.findByCreateUserIdAndLostId(userId,lostId);

      list.setState("已找到");

      return R.ok(list);
   }


}
